const express = require( 'express' );

const port = 8080 ;
const app = express();

let id = 1 ; // 用来表示学生编号
const students = [] ; // 用来存储学生信息

// staticMiddleware
app.use( express.static( 'public' ) );

// urlencodedMiddleware
app.use( express.urlencoded( { extended: false } ) );

app.post( '/add' , (req,resp,next)=>{
    let p = req.body ; // 从POST表单中获取请求参数
    if( !p.name ) {
        resp.send( '<h3>姓名不可为空</h3><a href="/add.html">返回</a>' );
        return ;
    }
    if( !p.gender ) {
        resp.send( '<h3>请选择性别</h3><a href="/add.html">返回</a>' );
        return ;
    }
    if( !p.birthdate ) {
        resp.send( '<h3>请确定出生日期</h3><a href="/add.html">返回</a>' );
        return ;
    }
    next();
});

// addMiddleware
app.post( '/add' , (req,resp)=>{
    let p = req.body ; // 从POST表单中获取请求参数
    p.id = id++ ;
    students.push( p );
    // resp.send( '<h3>添加成功</h3>' );
    resp.redirect( '/list' );
});

app.get( '/list' , (req,resp)=>{
    let content = '<table border="1" align="center" width="80%">';
    if( students.length == 0 ) {
        content += '<tr> <td align="center">暂无学生数据</td> </tr>' ;
    } else {
        students.forEach( s => {
            content += '<tr>' ;
            content += `<td>${s.id}</td>` ;
            content += `<td>${s.name}</td>` ; 
            content += `<td>${s.gender=='male'?'靓仔':'靓妹'}</td>` ; 
            content += `<td>${s.birthdate}</td>` ; 
            content += `<td><a href="/remove/${s.id}">删除</a></td>` ; 
            content += `<td><a href="/edit/${s.id}">编辑</a></td>` ; 
            content += '</tr>' ;
        });
    }
    content += '</table>' ;
    content += '<p align="center"><a href="/add.html">继续添加</a></p>' ;
    resp.send( content );
});

// 路由参数
app.get( '/remove/:id' , (req,resp) => {
    let id = req.params.id ;
    console.log( id );
    let index = students.findIndex( s => s.id == id );
    console.log( index );
    console.log( students );
    students.splice( index , 1 );
    console.log( students );
    resp.redirect( '/list' );
})

app.get( '/edit/:id' , (req,resp) => {
    let id = req.params.id ;
    let stu = students.find( s => s.id == id );
    let content = '<form action="/edit" method="post">' ;
    content += `<input type="hidden" name="id" value="${stu.id}">` ; 
    content += `<input type="text" name="name" value="${stu.name}">` ; 
    content += `<input type="radio" name="gender" value="male" ${stu.gender=='male'?'checked':''} >靓仔`;
    content += `<input type="radio" name="gender" value="female" ${stu.gender=='female'?'checked':''} >靓妹`;
    content += `<input type="date" name="birthdate" value="${stu.birthdate}">` ; 
    content += '<button type="submit">修改</button>' ;
    content += '</form>';
    resp.send( content );
});

app.post( '/edit' , (req,resp) => {
    let p = req.body ;
    let stu = students.find( s => s.id == p.id );
    stu.name = p.name ;
    stu.gender = p.gender ;
    stu.birthdate = p.birthdate ;
    resp.redirect( '/list' );
});

app.listen( port );